﻿using LiteBlog.Components.Contracts;
using LiteBlog.Controllers.Contracts;
using LiteBlog.Controllers.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace LiteBlog.Controllers
{
    public abstract class CompController<T, U> : BaseController, ICompController<T, U>
    {
        protected IComp<T, U> _component;

        public V GetComponent<V>()
        {
            return (V)_component;  
        }

        public CompController(IComp<T, U> component, ISettingsComp settingsComp, ICacheComp cacheComp)
            : base(settingsComp, cacheComp)
        {
            _component = component;
        }

        [HttpGet]
        [Authorize]
        [PageExceptionFilter]
        public virtual ActionResult Manage()
        {
            var collection = _component.Get();
            return View("Manage", GetAdminLayout(), collection);
        }

        [HttpPost]
        [Authorize]
        [ValidateFilter]
        [AjaxExceptionFilter]
        public virtual ActionResult Create(T model)
        {
            var result = _component.Create(model);
            var resultModel = GetResultModel(result, GetMessageParams(model));
            return Json(resultModel);
        }


        [HttpPost]
        [Authorize]
        [ValidateFilter]
        [AjaxExceptionFilter]
        public virtual ActionResult Update(string olid, T model)
        {
            var result = _component.Update(olid, model);
            var resultModel = GetResultModel(result, GetMessageParams(model));
            return Json(resultModel);
        }

        [Authorize]
        [AjaxExceptionFilter]
        public virtual ActionResult Delete(U id)
        {
            var model = _component.Get(id);
            var result = _component.Delete(id);
            var resultModel = GetResultModel(result, GetMessageParams(model));
            return Json(resultModel, JsonRequestBehavior.AllowGet);
        }

        protected virtual string[] GetMessageParams(T model)
        {
            return new string[] { string.Empty, string.Empty };
        }

        public abstract void ResolveComponents();
    }
}
